const ocrData = {
    data() {
        return {
            voicelist: [],
            showZznd: false,
            searchText: '',
            stopChatdata:true,
            voicing: false,
            addedPreview1: '',
            slocalResPath1: [],
            addedPreviewFile1: [],
            isFlagStartTitle: false,
            flag: true,
            show: false,
            showText: false,
            fileId: '',
            sessionId: '',
            source: null,
            count: 0,
            messages_show: [],
            meaaageText: [],
            messages: [],
            time1: 30, // 单次使用时长
            timetimer1: null, //控制语音30秒定时器

        }
    },
    filters: {
        textNum: (value) => {
            if (!value) return "";
            let data = value.split("");
            if (data.length < 15) {
                return value;
            }
            return value.slice(0, 15) + "...";
        },
    },
    mounted() {
        // var a = "李宇昂"
        // setInterval(() => {
        //     this.count++
        //     this.contentData(a)
        // },1000)
    },
    methods: {
        closedVansheet(){
           this.searchText = ''
           this.messages_show = []
        },
        stopChat() {
          this.stopChatdata = false
          this.chatting = true
        },
        zzndBtn() {
            let userId = sessionStorage.getItem("userId");
            let timestamp = new Date().getTime() + ""
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            let data = {
                type: "pzwd",
                timestamp: timestamp
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(data)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port +
                    "/tjAiAssistant/api/createSession",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    console.log(xhr.getResponseHeader("sign"), "xhr.getResponseHeader(si")
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                console.log(res.resultValue.data, " res.resultValue.data")
                                this.sessionId = res.resultValue.data.sessionId
                                this.functionBtn1()
                                this.showZznd = true
                                console.log(res.resultValue, 888)
                            }

                        } else {
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    } else {
                        mui.toast('完整性校验失败', {
                            duration: 'long',
                            type: 'div'
                        })
                    }

                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请求异常,请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },

            });
        },
        // 点击上传照片逻辑
        functionBtn1() {
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ["original"], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
                quality: 0.5, //压缩质量，范围0～1，数值越小，质量越低，压缩率越高（仅对jpg有效）
                success: (res) => {
                    this.slocalResPath1 = [];
                    // $(".curtain").css("display", "block");
                    // var exists = this.addedPreviewFile11.length;
                    // 先把数组长度固定
                    // this.addedPreview.length = exists + res.localIds.length;
                    // console.log(res.localIds, "id大小");
                    this.loopList1(res.localIds);
                },
            });
        },
        loopList1(localIds) {
            wx.invoke(
                "getLocalResPath", {
                    localId: localIds,
                },
                (res) => {

                    this.slocalResPath1.push(res.localResPath);
                    wx.getLocalImgData({
                        localId: localIds,
                        success: (res) => {
                            var localData = res.localData;
                            if (localData.indexOf("data:image") != 0) {
                                //判断是否有这样的头部
                                localData = "data:image/jpeg;base64," + localData;
                            }
                            localData = localData
                                .replace(/\r|\n/g, "")
                                .replace("data:image/jpg", "data:image/jpeg");
                            // 第一个替换的是换行符，第二个替换的是图片类型，因为在IOS机上测试时看到它的图片类型时jgp，
                            // 这不知道时什么格式的图片，为了兼容其他设备就把它转为jpeg
                            this.addedPreview1 = localData

                            this.extNetUpload();
                        },
                    });

                }
            );
        },

        extNetUpload() {
            var channelId = "net_upload_" + createNonceStr(8);
            let userId = sessionStorage.getItem("userId");
            const timestamp = new Date().getTime() + "";
            let signTime = sm3(timestamp + "&" + userId)
            console.log(this.sessionId, "this.sessionId")
            let AuthenticationSession =
                sessionStorage.getItem("Authentication");
            var datas = {
                    type: "pzwd",
                    sessionId: this.sessionId
                },

                files = {}
            this.slocalResPath1.forEach((item, index) => {
                files['file'] = item
            })
            var param = {
                id: channelId,
                timeout: "60",
                url: localUrlLink +
                    iscp_port +
                    "/tjAiAssistant/api/uploadFile",
                header: {
                    "Content-Type": "application/json;charset=UTF-8",
                    sign: signTime,
                    Authentication: AuthenticationSession,
                    timestamp: timestamp,
                    userId: userId,
                },
                data: datas,
                files: files,
            };
            console.log("ext_Net_Upload---param", param);
            wx.invoke(
                "ext_Net_Upload", {
                    data: param,
                },
                (res) => {
                    console.log('ext_Net_Upload--res', res)
                    if (res.err_msg.endsWith(":ok")) {
                        //成功结果
                        const result = JSON.parse(res.result);
                        if (result.code == 200) {
                            console.log(result.resultValue.data.fileId, "data.fileId")
                            this.fileId = result.resultValue.data.fileId
                            this.messages_show.push({
                                "role": "user",
                                "content": '',
                                "img": this.addedPreview1,
                            })
                            this.fileText()
                        }

                    }
                }
            );
        },
        fileText(num) {
            let that = this
            if (num == 1) {
                if (!that.searchText || that.searchText.split(" ").join("").length == 0) {
                    mui.toast('问题不能为空', {
                        duration: 'long',
                        type: 'div'
                    })
                    return
                }
                that.messages_show.push({
                    "role": "user",
                    "content": that.searchText,
                    "img": '',
                })
            }
            this.searchText = ''
            let userId = sessionStorage.getItem("userId");
            let Authentication = sessionStorage.getItem("Authentication");
            let iscp_port;
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = "";
            }
            let timestamp = new Date().getTime() + ""
            let data = {
                type: "pzwd",
                sessionId: that.sessionId,
                fileId: that.fileId,
                timestamp: timestamp,
                text: that.searchText == "" ? "识别图片" : that.searchText

            };
            data = JSON.stringify(data);

            //转数据为json字符串
            //创建sse对象，请求地址，参数，请求方法
            that.source = new SSE(localUrlLink + iscp_port + "/tjAiAssistant/api/runSession", {
                headers: {
                    'Content-Type': 'application/json'
                },
                payload: data,
                method: 'POST'
            });

            //与后台连接成功触发的监听
            that.source.addEventListener('open', function (e) {
                console.log("open")
                console.log('连接成功');
               that.chatting = true

            });

            //接收到后台数据触发监听方法
            that.source.addEventListener('message', function (event) {
                that.contentData(event)
            });

            //请求出错触发的监听方法
            that.source.addEventListener('error', function (e) {
                console.error('请求出错：', e);
            });

            //数据传输完成关闭连接触发的监听方法
            that.source.addEventListener('close', function (e) {
                console.log('连接关闭');
            });

            //调用发起请求
            that.source.stream();

        },
        contentData(event) {
            if (event.data && this.stopChatdata) {
                event = event.data.slice(5)
                const date = JSON.parse(event).data
                console.log(date, 667888)
                // this.meaaageText.push(date)
                if (this.count == 0) {
                    this.messages_show.push({
                        "count": this.count,
                        "role": "assistant",
                        "content": date.answer,
                    })
                    this.count ++
                } else{
                  
                    if(date.isEnd){
                        this.count = 0
                        this.chatting = false
                        return
                    } 
                    this.messages_show[this.messages_show.length - 1].content +=  date.answer
                }
                
            }
        },
        demo() {
            // 判断光标是点击的0位还是默认直接说话
            var $input1 = document.getElementById("titleInput");
            if ($input1.selectionStart == 0) {
                this.isFlagStartTitle = true
            }
        },
        start() {
            this.voicing = true
            $(this).addClass("stop");
            let i = 0;
            // $(this).data("interval",window.setInterval(function(){
            //     $(".record-time").html((++i)+"s");
            // },1000,i));
            wx.startRecord();
            let me = this;
            //30秒后录音自动停止
            this.time1 = 30;
            // 限时30秒说话时间，24秒的时候，提示，30秒后自动暂停
            this.timetimer1 = setInterval(() => {
                this.time1--;
                if (this.time1 == 6) {
                    mui.toast('5秒后结束！', {
                        duration: 1000,
                        type: 'div'
                    });
                }
                if (this.time1 == 0) {
                    // clearInterval(timetimer1);
                    this.suspend()
                }
            }, 1000);
            // 打开语音翻译功能
            wx.onVoiceRecordEnd({
                complete: (res) => {
                    let localId = res.localId;
                    if (localId) {
                        if (this.voicelist.findIndex((item) => item == localId) == -1) {
                            this.voicelist.push(localId);
                            this.listVoiceFile(this.voicelist);
                        }
                    }
                    $(me).click();
                }
            });
            this.flag = false
            $(".startD").css("marginTop", "0rem")
        },
        ulli() {
            if ($(this).data("localId")) {
                this.voicelist.currentIndex = $(this).data("localId");
            }
        },
        text() {
            this.ulli()
            // if(this.voicelist.currentIndex){
            // 翻译出来的内容
            wx.translateVoice({
                localId: this.voicelist[this.voicelist.length - 1],
                isShowProgressTips: 1,
                success: (res) => {
                    var $input = document.getElementById("titleInput");
                    if (this.isFlagStartTitle == true) {
                        this.searchText = this.searchText.slice(",", $input.selectionStart) + res.translateResult + this.searchText.slice($input.selectionStart)
                        this.isFlagStartTitle = false
                    } else {
                        if ($input.selectionStart == 0) {
                            this.searchText += res.translateResult
                        } else if (this.searchText.length == $input.selectionStart) {
                            this.searchText += res.translateResult
                        } else {
                            this.searchText = this.searchText.slice(",", $input.selectionStart) + res.translateResult + this.searchText.slice($input.selectionStart)
                        }
                    }
                }
            });
        },
        listVoiceFile(voices) {
            for (let voice of voices) {
                let isExist = false;
                if (!isExist) {
                    let li = $("<li>音频-" + voice + "</li>");
                    li.data("localId", voice);
                    $(".voice-list").append(li);
                }
            }
        },
        // 暂停
        suspend() {
            this.voicing = false
            clearInterval(this.timetimer1)
            this.time1 = 30
            this.time = clearInterval(this.time)
            // if($(this).hasClass("stop")){
            $(this).removeClass("stop");
            window.clearInterval($(this).data("interval"));
            $(".record-time").html("");
            // 暂停
            wx.stopRecord({
                success: (res) => {
                    let localId = res.localId;
                    if (localId) {
                        if (this.voicelist.findIndex((item) => item == localId) == -1) {
                            this.voicelist.push(localId);
                            this.listVoiceFile(this.voicelist);
                            this.text()
                        }
                    }
                }
            });
            // }
        },
        listVoiceFile(voices) {
            for (let voice of voices) {
                let isExist = false;
                $(".voice-list").children().each(function () {
                    if ($(this).data("localId") == voice) {
                        isExist = true;
                    }
                });
                if (!isExist) {
                    let li = $("<li>音频-" + voice + "</li>");
                    li.data("localId", voice);
                    $(".voice-list").append(li);
                }
            }
        },
        sendMail(item) {
            console.log(item)
            userId = sessionStorage.getItem("userId");
            orgId = sessionStorage.getItem("unitId");
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = "";
            }
            let timestamp = new Date().getTime() + ""
            let data = {
                userId: userId,
                orgId: orgId,
                imgUrl: item.img ? item.img : '',
                messages: item.content,
                timestamp: timestamp,
            }
            data = JSON.stringify(data);
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let sign = sm3(data);
            $.ajax({
                method: "POST",
                url: localUrlLink + iscp_port + "/tjAiAssistant/answering/yiyanSendMail",
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign,
                    userId: userId,
                    timestamp: timestamp,
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                mui.toast('邮箱发送成功', {
                                    duration: 'long',
                                    type: 'div'
                                })
                            } else {
                                mui.toast('令牌校验失败', {
                                    duration: 'long',
                                    type: 'div'
                                })
                            }
                        } else {
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    } else {
                        mui.toast('完整性校验失败', {
                            duration: 'long',
                            type: 'div'
                        })
                    }
                },
                error: function (e) {
                    mui.toast("请求异常，请稍后再试！", {
                        duration: 'long',
                        type: 'div'
                    })
                },
            })
        },
    }
}